'''
Created on 2018年2月20日

@author: heguofeng
disk form pythonanywhere
'''
import unittest
import requests

class DiskPAW(object):
    def __init__(self,userid,config={}):
        self.userid = userid
        self.url = config.get("pythonanywhere_url","http://joygame2.pythonanywhere.com/safebook/")
        self.isLogin = False
        
    def login(self):
        self.isLogin = True
        pass
    
    def read(self):
        if not self.isLogin:
            return ""
        payload = {"userid":self.userid}
        response = requests.get(self.url+"download",params = payload)
#         print(response.text)
        return response.text
    
    def write(self,data):
        if not self.isLogin:
            return False
        tempfile = open("tmp","wb")
        tempfile.write(data)
        tempfile.close()
        with open("tmp","rb") as filedata:
            files = {"datafile":("safebook.sbr",filedata)}
            payload = {"userid":self.userid}
            response = requests.post(self.url+"upload",params = payload, files = files)
#             print(response.url)
#             print(response.request.headers)
#             print(response.text)
            return True


class Test(unittest.TestCase):


    def setUp(self):
        self.disk = DiskPAW("heguofeng")
        pass


    def tearDown(self):
        pass


    def testLoginWriteRead(self):
        self.disk.login()
        self.assertTrue(self.disk.isLogin, "Success login.")
#         result = self.disk.write("heguofeng".encode())
#         self.assertTrue(result, "Write heguofeng to safebook.sbr.")
        result = self.disk.read()
        self.assertEqual(result, "heguofeng", "read safebook.sbr.")
        pass



if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()